package service;

import com.fr.base.FRContext;
import com.fr.script.AbstractFunction;
import com.fr.stable.Primitive;
import com.fr.stable.StringUtils;
import com.wondersgroup.hs.mobile.nursing.rpc.service.ReportService;
import dao.JDBCConn;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.Level;

import static util.ConstantSetUp.passWord;
import static util.ConstantSetUp.url;
import static util.ConstantSetUp.user;

/**
 * Created by Xtra on 4/5 0005.
 */
public class MulitItemQuery extends AbstractFunction {


    ReportService reportService;

    @Override
    public Object run(Object[] objects) {
        String result = "";
        try {
            String documentID = (String) objects[0];
            String templateCode=(String) objects[1];
            String displayTitle = (String) objects[2];
            if (!StringUtils.isEmpty(documentID) || !StringUtils.isEmpty(displayTitle)) {
                String sql1 = "select c_content from dbo.t_mb_emr_docValue where c_document = '"+documentID+"' and c_item = " +
                        "(select c_itemID from dbo.t_mb_emr_items where c_displayTitle='"+displayTitle+"' and c_template='"+templateCode+"')";
                JDBCConn jdbcConn = new JDBCConn();
                FRContext.getLogger().log(Level.INFO, "链接数据库192.168.0.60中：---{数据库url:" + url + ",登录名：nurse}!");
                jdbcConn.getConnection(url, user, passWord);
                FRContext.getLogger().log(Level.INFO, "准备执行SQL语句：**{" + sql1 + "}!");
                String dispId = jdbcConn.executeQuery(sql1);
                String[] disp=dispId.split(";");
                for (String optionid:disp) {
                    String sql="SELECT  t_mb_emr_option.c_title FROM t_mb_emr_option WHERE c_optionID='"+optionid+"'";
                    String titleValue=jdbcConn.executeQuery(sql);
                    result=result+";"+titleValue;
                }
                result=result.replaceFirst(";","");
                jdbcConn.close();
            } else {
                FRContext.getLogger().log(Level.WARNING, "SQL执行异常！请检查数据或插件！插件名：plugin-MulitItemQuery");
                return Primitive.ERROR_VALUE;
            }
            FRContext.getLogger().log(Level.INFO, "SQL执行完毕！输出结果！-----"+result);
        } catch (Exception e) {
            StringWriter stringWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(stringWriter);
            e.printStackTrace(printWriter);
            FRContext.getLogger().log(Level.WARNING, stringWriter.toString());
        }
        return result;
    }
}
